﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Service.Framework.Utils
{
    public class JsonHelper
    {


        /// <summary>
        /// 不序列化某些属性,空字段不序列化
        /// </summary>
        /// <param name="o">对象</param>
        /// <param name="props">序列化设置</param>
        /// <returns></returns>
        public static string SerializeObjectWithoutSomePros(object o, String[] props)
        {
            JsonSerializerSettings jsettings = new JsonSerializerSettings();
            jsettings.ContractResolver = new LimitPropsContractResolver(props, false);
            jsettings.NullValueHandling = NullValueHandling.Ignore;
            string json = JsonConvert.SerializeObject(o, Newtonsoft.Json.Formatting.None, jsettings);
            return json;
        }

        /// <summary>
        /// 序列化某些属性,空字段不序列化
        /// </summary>
        /// <param name="o">对象</param>
        /// <param name="props">序列化设置</param>
        /// <returns></returns>
        public static string SerializeObjectWithSomePros(object o, String[] props)
        {
            JsonSerializerSettings jsettings = new JsonSerializerSettings();
            jsettings.ContractResolver = new LimitPropsContractResolver(props, false);
            jsettings.NullValueHandling = NullValueHandling.Ignore;
            string json = JsonConvert.SerializeObject(o, Newtonsoft.Json.Formatting.None, jsettings);
            return json;
        }


        /// <summary>
        /// 将对象序列化为JSON格式
        /// </summary>
        /// <param name="o">对象</param>
        /// <returns>json字符串</returns>
        public static string SerializeObject(object o)
        {
            string json = JsonConvert.SerializeObject(o);
            return json;
        }

        /// <summary>
        /// 解析JSON字符串生成对象实体
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="json">json字符串(eg.{"ID":"112","Name":"石子儿"})</param>
        /// <returns>对象实体</returns>
        public static T DeserializeJsonToObject<T>(string json) where T : class
        {
            JsonSerializer serializer = new JsonSerializer();
            StringReader sr = new StringReader(json);
            object o = serializer.Deserialize(new JsonTextReader(sr), typeof(T));
            T t = o as T;
            return t;
        }

        /// <summary>
        /// 解析JSON数组生成对象实体集合
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="json">json数组字符串(eg.[{"ID":"112","Name":"石子儿"}])</param>
        /// <returns>对象实体集合</returns>
        public static List<T> DeserializeJsonToList<T>(string json) where T : class
        {
            JsonSerializer serializer = new JsonSerializer();
            StringReader sr = new StringReader(json);
            object o = serializer.Deserialize(new JsonTextReader(sr), typeof(List<T>));
            List<T> list = o as List<T>;
            return list;
        }

        /// <summary>
        /// 反序列化JSON到给定的匿名对象.
        /// </summary>
        /// <typeparam name="T">匿名对象类型</typeparam>
        /// <param name="json">json字符串</param>
        /// <param name="anonymousTypeObject">匿名对象</param>
        /// <returns>匿名对象</returns>
        public static T DeserializeAnonymousType<T>(string json, T anonymousTypeObject)
        {
            T t = JsonConvert.DeserializeAnonymousType(json, anonymousTypeObject);
            return t;
        }


        /// <summary>
        /// 序列化json字符串为制定对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="strJson"></param>
        /// <returns></returns>
        public static T JsonDeserialize<T>(string strJson)
        {
            try
            {
                return JsonConvert.DeserializeObject<T>(strJson);
            }
            catch (Exception e)
            {

                WriteErrorMessage("JsonDeserialize", "Json=" + strJson + "。" + e.Message);
            }
            return default(T);
        }

        /// <summary>
        /// 根据一个json字符串反序列化为一个json对象
        /// </summary>
        /// <param name="jsonString"></param>
        /// <returns></returns>
        public static JObject DeserializeToJObject(string jsonString)
        {
            try
            {
                return JObject.Parse(jsonString);
                // return (Newtonsoft.Json.Linq.JObject) JsonConvert.DeserializeObject(jsonString);
            }
            catch (Exception ex)
            {
                WriteErrorMessage("JsonHelper的DeserializeJObject", ex.Message);
                throw;
            }
        }

        public static JArray DeserializeToJArray(string jsonArrayString)
        {
            try
            {
                return JArray.Parse(jsonArrayString);
            }
            catch (Exception ex)
            {
                WriteErrorMessage("JsonHelper的DeserializeJArray", ex.Message);
                throw;
            }
        }


        private static void WriteErrorMessage(string strMethodName, string sErrorMessage)
        {
            DirectoryInfo clsPath = new DirectoryInfo(Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory));
            DirectoryInfo clsSubPath = clsPath.CreateSubdirectory("Errlog\\LBD_WebApiinterface\\Utility");

            if (clsSubPath.Exists)
            {
                DateTime clsDate = DateTime.Now;
                string strPath = clsSubPath.FullName + "\\JsonFormatter(" + String.Format("{0:yyyy-MM-dd}", clsDate) + ").log";
                StreamWriter clsWriter = new StreamWriter(strPath, true);
                clsWriter.WriteLine(String.Format("{0:HH:mm:ss}", clsDate) + " " + strMethodName + ": " + sErrorMessage);
                clsWriter.Close();
            }
        }
    }
}
